function addWXSubscribeMessageToService(callBack, params) {
  const accountInfo = wx.getAccountInfoSync();
  // env类型 develop:开发版、trial:体验版、release:正式版
  const env = accountInfo.miniProgram.envVersion;
  const states = {
    // 开发版
    develop: 'developer',
    // 体验版
    trial: 'trial',
    // 正式版
    release: 'formal'
  };
  // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
  const miniprogramState = states[env];
  if (callBack) callBack({ ...params, miniprogramState });
}

export function requestSubscribeMessage(tmplIds, callBack) {
  if (!tmplIds || !tmplIds.length) return;
  // let result;
  // if (shouldCheck) {
  //   result = await this.checkSubscribeMessageAuth(tmplIds);
  // }
  wx.requestSubscribeMessage({
    tmplIds, // 需要订阅的消息模板的id的集合，一次调用最多可订阅3条消息
    success: res => {
      //  { errMsg: "requestSubscribeMessage:ok", zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: "accept"}
      // 表示用户同意订阅zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE这条消息
      // console.log('requestSubscribeMessage', res);
      const { errMsg, ...rest } = res;
      if (errMsg === 'requestSubscribeMessage:ok') {
        // 动态的键，即模板id，值包括'accept'、'reject'、'ban'、'filter'
        const tmplIdsValues = tmplIds.map(id => res[id]);
        console.log('success', errMsg, rest, tmplIdsValues);
        let
        userClickCancel = false;
        if (tmplIdsValues.includes('reject')) { // 存在一个不同意订阅的消息，说明用户点击了取消
          console.log('用户点击了取消');
          userClickCancel = true;
        }
        // else if (tmplIdsValues.includes('accept')) {
        // }
        const tmplIdsAcceptValues = tmplIds.filter(id => res[id] === 'accept');
        // console.log('tmplIdsAcceptValues', tmplIdsAcceptValues);
        if (tmplIdsAcceptValues.length) {
          addWXSubscribeMessageToService(callBack, { tmplIdsAcceptValues, userClickCancel });
        } else addWXSubscribeMessageToService( callBack, {tmplIdsAcceptValues, isError: true, userClickCancel });
      } else {
        addWXSubscribeMessageToService( callBack, {tmplIdsAcceptValues: [], isError: true, userClickCancel });
      }
    },
    fail: error => {
      console.error('error', error);
      if (error.errCode === 20004) { // 订阅消息总开关 为关闭
        // this.showModalSetting();
      }
    }
  })
}

// 判断订阅模板消息中点击了“总是保持以上选择，不再询问”
export async function checkSubscribeMessageIsAlwaysTip({ tmplIds }) {
  return await new Promise((resolve, inject) => {
    wx.getSetting({
      withSubscriptions: true,
      success (res) {
        console.log(res.subscriptionsSetting);
        const {
          mainSwitch, // 订阅消息总开关，true为开启，false为关闭
          itemSettings = {} // itemSettings 只返回用户勾选过订阅面板中的“总是保持以上选择，不再询问”的订阅消息。(key:模板id, value: 'accept'、'reject'、'ban')
        } = res.subscriptionsSetting;
        // console.log('checkSubscribeMessageIsAlwaysTip1', tmplIds, itemSettings);
        if (!mainSwitch) {
          // showModalSetting(resolve);
          uni.showModal({
            title: '提示',
            content: '小程序想给你发送消息，请接收订阅消息后重试',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success (res) {
                    console.log('openSetting', res);
                    resolve({ openSetting: true });
                  }
                });
              } else if (res.cancel) {
                resolve({ mainSwitch: false });
              }
            }
          });
        } else {
          const existTmplIds = tmplIds.filter(id => !!itemSettings[id]); // 点击了“总是保持以上选择，不再询问”的（包含同意，不同意）订阅消息id
          const acceptTmplIds = tmplIds.filter(id => itemSettings[id] === 'accept'); // 点击了“总是保持以上选择，不再询问”的（同意）订阅消息id
          const rejectTmplIds = tmplIds.filter(id => itemSettings[id] === 'reject'); // 点击了“总是保持以上选择，不再询问”的（不同意）订阅消息id
          const isAlwaysTip = existTmplIds.length === tmplIds.length; // 如果订阅的消息全部都存在于itemSettings中，说明所有消息都点击了“总是保持以上选择，不再询问”
          console.log('checkSubscribeMessageIsAlwaysTip2', existTmplIds, acceptTmplIds, rejectTmplIds, isAlwaysTip);
          if (acceptTmplIds.length === tmplIds.length) { // （并且全部都点击的同意）
            resolve({ mainSwitch, isAlwaysTip, allAccept: true });
          } else if (rejectTmplIds.length === tmplIds.length) { // （并且全部都点击的不同意）
            resolve({ mainSwitch, isAlwaysTip, allReject: true });
          }  else if (existTmplIds.length === tmplIds.length) { // （包含同意，不同意）
            resolve({ mainSwitch, isAlwaysTip });
          } else if (existTmplIds.length) { // 订阅的模板消息至少有一个，点击了“总是保持以上选择，不再询问”（可能是同意或者不同意）
            //
            resolve({ mainSwitch, isAlwaysTip });
          } else resolve({ mainSwitch });
        }
      },
      fail (error) {
        console.error('getSetting', error);
        resolve({ error });
      },
    });
  });
}
